package cn.yunyichina.provider.base.thread;

import cn.yunyichina.provider.base.dao.DoctorDao;
import cn.yunyichina.provider.base.entity.Doctor;
import cn.yunyichina.provider.base.vo.WardsRequest;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.wards.DoctorListVoResponse;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by 15-AK on 2017/1/7.
 */
public class DoctorListSaveRunnable implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(DoctorListSaveRunnable.class);

    private List<DoctorListVoResponse> doctorListVoResponse;
    private WardsRequest request;


    public DoctorListSaveRunnable(List<DoctorListVoResponse> doctorListVoResponse,WardsRequest request) {
        this.doctorListVoResponse = doctorListVoResponse;
        this.request = request;
    }

    @Override
    public void run() {

        // 查询组织信息-----------------------------------------------start
        Map<String, String> orgParamMap = new HashMap<String, String>();
        orgParamMap.put("org_code", request.getHospitalCode());
        logger.info("【医生列表-查询组织信息】, yyt.base.branchhospital.org.list request=" + JSON.toJSONString(orgParamMap));
        Response orgResponse = BaseService.callUnderlineFromInternal("yyt.base.branchhospital.org.list", JSON.toJSONString(orgParamMap));
        logger.info("【医生列表-查询组织信息】, yyt.base.branchhospital.org.list response=" + JSONObject.toJSONString(orgResponse));
        if (!"0".equals(orgResponse.getResultCode())) {
            throw new CallException("1003","找不到机构信息 by org_code=" + request.getHospitalCode());
        }
        List<Org> orgList = JsonUtils.parseArray(orgResponse.getResult(), Org.class);
        if (CollectionUtils.isEmpty(orgList)) {
            throw new CallException("1004","找不到机构信息 by org_code=" + request.getHospitalCode());
        }
        Org org = orgList.get(0);


        DoctorDao doctorDao = SpringContextHandler.getBean(DoctorDao.class);
        List<Doctor> dbDoctorList = doctorDao.selectByHospitalCode(request.getHospitalCode());
        Map<String ,Doctor> dbDoctorMap = new HashMap<>();
        Map<String ,Doctor> hisDoctorMap = new HashMap<>();

        for (Doctor doc :dbDoctorList){
            dbDoctorMap.put(doc.getDoctorCode(),doc);
        }

        for (DoctorListVoResponse vo :doctorListVoResponse){
            Doctor doctor = buildDoctor(org, vo);
            hisDoctorMap.put(doctor.getDoctorCode(),doctor);
        }

        List<Doctor> needSaveDoctors = new ArrayList<>();
        for (String doctorCode :hisDoctorMap.keySet()){
            Doctor dbDoctor = dbDoctorMap.get(doctorCode);
            //数据库还没有该医生
            if (dbDoctor == null){
                needSaveDoctors.add(hisDoctorMap.get(doctorCode));
            }
        }

        if (com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(needSaveDoctors)){
            doctorDao.batchInsert(needSaveDoctors);
        }

    }

    private Doctor buildDoctor(Org org, DoctorListVoResponse vo) {
        Doctor doctor = new Doctor();
        doctor.setId(PKGenerator.generateId());
        doctor.setName(vo.getDoctorName());
        doctor.setDepartmentId(vo.getDeptCode());
        doctor.setDepartmentName(vo.getDeptName());
        doctor.setHospitalId(org.getId());
        doctor.setHospitalCode(org.getOrgCode());
        doctor.setHospitalName(org.getOrgName());
        doctor.setBranchId("");
        doctor.setBranchName("");
        // doctor.setTitle();
        doctor.setImg(vo.getDoctorPic());
        doctor.setMobile(vo.getDoctorMobile());
        doctor.setIdNo("");
        if(StringUtils.isBlank(vo.getDoctorBirth())){
            doctor.setBirth(DateUtils.dateToString(new Date()));
        }else{
            doctor.setBirth(vo.getDoctorBirth());
        }

        doctor.setSex(Integer.parseInt(vo.getDoctorSex()));

        doctor.setNumber("");
        doctor.setDisc(vo.getDoctorIntrodution());
        doctor.setSkilled(vo.getDoctorSkill());
        // doctor.setStatus();
        doctor.setCardNo("");
        doctor.setMedicalcardNo("");
        doctor.setDoctorCode(vo.getDoctorCode());
        doctor.setRatio("");
//        doctor.setEntryTime("");
//        doctor.setRetirementTime("");
//        doctor.setDepartureTime("");
//        doctor.setDeathTime("");
//        doctor.setLossTime("");
        doctor.setCreatedTime(DateUtils.dateToString(new Date()));
        doctor.setUpdateTime(DateUtils.dateToString(new Date()));
        //doctor.setDelStatus();
        doctor.setPassword(vo.getPassword());
        return doctor;
    }
}
